package com.cheer.ba.view.activity;

import android.content.Intent;
import android.os.Handler;
import android.text.Editable;
import android.text.Html;
import android.text.Layout;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.app.App;
import com.cheer.ba.app.oss.OssManager;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.H5Address;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.CheerCircleModel;
import com.cheer.ba.model.CommentModel;
import com.cheer.ba.model.TagModel;
import com.cheer.ba.presenter.impl.CommentPresenter;
import com.cheer.ba.utils.ImageUtils;
import com.cheer.ba.utils.Protect;
import com.cheer.ba.utils.ShareNewsUtil;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.view.base.CommonAdapter;
import com.cheer.ba.view.base.ViewHolder;
import com.cheer.ba.widget.MyListView;
import com.cheer.ba.widget.ShowPopupView;
import com.cheer.ba.widget.headview.CheerHeadView;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;
import org.xml.sax.XMLReader;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 加油啦详情
 * Created by Hq on 2017/7/21.
 */
public class CheerCircleDetailAty extends BaseCommAty implements ShowPopupView.OnItemPopupClick, AdapterView.OnItemClickListener {

    @BindView(R.id.id_detail_xrefreshv)
    XRefreshView mXRefreshView;
    @BindView(R.id.id_detail_head_img)
    ImageView mImgHead;
    @BindView(R.id.id_detail_name_txt)
    TextView mTxtUserName;
    @BindView(R.id.id_detail_time_txt)
    TextView mTxtUserTime;
    @BindView(R.id.id_detail_del_txt)
    TextView mTxtDel;
    @BindView(R.id.id_detail_line)
    View mLine;
    @BindView(R.id.id_detail_tag_txt)
    TextView mTxtTag;

    @BindView(R.id.id_detail_webview)
    WebView mMyWebView;

    @BindView(R.id.id_detail_location_txt)
    TextView mTxtLocation;
    @BindView(R.id.id_detail_zan_img)
    ImageView mImgZan;
    @BindView(R.id.id_detail_zan_txt)
    TextView mTxtZanNum;
    @BindView(R.id.id_detail_zan_list_txt)
    TextView mTxtZanList;
    //存储点赞列表
    private List<CommentModel> mSaveZanList = new ArrayList<CommentModel>();
    private CommentModel mSaveUserZan = new CommentModel();

    @BindView(R.id.id_detail_comment_txt)
    TextView mTxtComment;
    //评论列表
    //暂无评论
    @BindView(R.id.id_detail_no_comment_txt)
    TextView mTxtNoComment;
    @BindView(R.id.id_detail_listv)
    MyListView mCommentListv;
    private CommonAdapter<CommentModel> mCommentAdp;
    private List<CommentModel> mTotalModel = new ArrayList<CommentModel>();

    //弹出头像框
    private ShowPopupView popupView;
    public static final String[] POPUP_ITEMS = {"删除"};
    public static final int[] POPUP_ITEMS_COLOR = {R.color.red};
    private ShareNewsUtil mShare;

    //是否已经导入
    private boolean hasLoad;
    private CheerCircleModel model;
    //记录删除评论或者回复的model
    private CommentModel mRecordCommentItem;

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_circle_detail, null, false));
    }

    @Override
    public void initPresenter() {
        presenter = new CommentPresenter();
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    @Override
    public void initView() {
        setTitleText("详情");

        mSaveUserZan.custNname = Session.getUserName();
        mSaveUserZan.custImg = Session.getUserPicUrl().replace(OssManager.OSS_HOST, "");
        mSaveUserZan.custId = Session.getUserId();

        model = (CheerCircleModel) getIntent().getSerializableExtra(IntentKey.General.KEY_MODEL);

        popupView = new ShowPopupView(aty);
        popupView.setItemColor(POPUP_ITEMS_COLOR);
        popupView.setOnItemPopupClick(this);

        setXRefreshView(mXRefreshView, true, false, false, false, new CheerHeadView(aty), null);
        mXRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(final boolean isPullDown) {
                loadData(false);
            }
        });
        if (null != model) {
            ImageUtils.showRoundImg(aty, Protect.setPic(model.custImg), R.drawable.ic_user_head, R.drawable.ic_user_head, mImgHead);
            mTxtUserName.setText(model.custNname);
            mTxtUserTime.setText(StringUtils.getDetailStr(model.createTime));
            if (TextUtils.equals(Session.getUserId(), model.custId)) {
                mTxtDel.setVisibility(View.VISIBLE);
//                mLine.setVisibility(View.VISIBLE);
            } else {
                mTxtDel.setVisibility(View.INVISIBLE);
//                mLine.setVisibility(View.INVISIBLE);
            }
            handTag();
            configWebView();
            if (StringUtils.isEmpty(model.location)) {
                mTxtLocation.setVisibility(View.INVISIBLE);
            } else {
                mTxtLocation.setVisibility(View.VISIBLE);
                mTxtLocation.setText(model.location);
            }
            handZan();
            loadData(false);
            //处理评论列表
            List<CommentModel> mComments = model.getCommentList();
            mTotalModel.clear();
            mTotalModel.addAll(mComments);
        } else {
            dataStatus(2);
        }
    }

    /**
     * 加载数据
     */
    public void loadData(boolean isShowLoade) {
        ((CommentPresenter) presenter).getUserZanList(isShowLoade, "12", model.sourceId);
        stopRefresh(mXRefreshView, 2000);
    }

    @Override
    public void initData() {
        mCommentAdp = new CommonAdapter<CommentModel>(aty, mTotalModel, R.layout.adp_detail_comment) {
            @Override
            public void convert(ViewHolder helper, CommentModel item) {
                ImageUtils.showCircleImg(aty, Protect.setPic(item.custImg), R.drawable.ic_user_head, R.drawable.ic_user_head, (ImageView) helper.getView(R.id.id_comment_head_img));
                helper.setText(R.id.id_comment_name_txt, item.custNname);
                helper.setText(R.id.id_comment_time_txt, StringUtils.getDetailStr(item.releaseDate));
                TextView mTxtContent = helper.getView(R.id.id_comment_context_txt);

                String content = "";
                //1评论 2回复
                int cmtType = item.cmtType;
                if (cmtType == 1) {
                    content = "";
                } else {
                    content = "回复 " + item.replyCustNname + ": ";
                }
                if (item.delFlag == 0) {
                    content += item.context;
                } else {
                    content += "评论已删除";
                }
                mTxtContent.setText(content);
            }
        };
        mCommentListv.setAdapter(mCommentAdp);
        mCommentListv.setOnItemClickListener(this);
        handComment();
    }

    @Override
    public void OnItemClick(int position, String tag) {
        //删除评论或者回复
        ((CommentPresenter) presenter).delMyComment(false, mRecordCommentItem.uid);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (isLogin(true)) {
            CommentModel commentModel = (CommentModel) mCommentAdp.getItem(position);
            mRecordCommentItem = commentModel;
            if (commentModel.delFlag == 0) {
                if (TextUtils.equals(Session.getUserId(), commentModel.custId)) {
                    //自己的评论
                    popupView.showAtLocPop(mRootViewLL, POPUP_ITEMS);
                } else {
                    //回复别人的评论
                    ((CommentPresenter) presenter).showCommentPop(mRootViewLL, "2", "回复 " + commentModel.custNname + "：", false);
                }
            }
        }
    }

    @OnClick({R.id.id_forward_rela, R.id.id_detail_comment_rela, R.id.id_detail_del_txt, R.id.id_circle_like_linear, R.id.id_detail_comment_txt})
    public void onClick(View mView) {
        switch (mView.getId()) {
            case R.id.id_forward_rela:
                //分享
                String context = model.title.replaceAll("<br/>", "");
                mShare = new ShareNewsUtil(aty, context, "加油省钱？选加油啦错不了！", H5Address.FORWARD_APP + model.webUrl + "?s=true", "");
                mShare.showShare();
                break;
            case R.id.id_detail_del_txt:
                //删除
                ((CommentPresenter) presenter).delDynamic(true, model.uid);
                break;
            case R.id.id_detail_comment_rela:
            case R.id.id_detail_comment_txt:
                //评论
                if (isLogin(true)) {
                    ((CommentPresenter) presenter).showCommentPop(mRootViewLL, "1", "评论：", false);
                }
                break;
            case R.id.id_circle_like_linear:
                //点赞
                if (isLogin(true)) {
                    if (model.goodStatus == 1) {
                        //取消点赞
                        ((CommentPresenter) presenter).userDelOperation(true, "4", "12", model.sourceId);
                    } else {
                        //点赞
                        ((CommentPresenter) presenter).userOperation(true, "4", "12", model.sourceId);
                    }
                }
                break;
        }
    }

    /**
     * 处理点赞
     */
    public void handZan() {
        if (model.goodStatus == 1) {
            mImgZan.setSelected(true);
        } else {
            mImgZan.setSelected(false);
        }
        mTxtZanNum.setText(model.goodCount == 0 ? "" : (model.goodCount + ""));
        if (mSaveZanList.isEmpty()) {
            mTxtZanList.setVisibility(View.GONE);
        } else {
            mTxtZanList.setVisibility(View.VISIBLE);
            mTxtZanList.setText("");
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mSaveZanList.size(); i++) {
                CommentModel model = mSaveZanList.get(i);
//                String str = "<font color='#E69215'style='border:1px solid red;'>" + model.custNname + "</font>" + "、";
                String str = model.custNname + "、";
                sb.append(str);
            }
            sb.deleteCharAt(sb.length() - 1);
            mTxtZanList.setText(sb.toString());
        }
    }

    /**
     * 处理评论
     */
    public void handComment() {
        mTxtComment.setText(model.commentCount == 0 ? "" : (model.commentCount + ""));
        if (null != mTotalModel && !mTotalModel.isEmpty()) {
            mCommentListv.setVisibility(View.VISIBLE);
            mTxtNoComment.setVisibility(View.GONE);
            mCommentAdp.notifyDataSetChanged();
        } else {
            mCommentListv.setVisibility(View.GONE);
            mTxtNoComment.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 处理显示H5
     */
    private void configWebView() {
        WebSettings settings = mMyWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAllowFileAccess(true);
        settings.setDefaultTextEncodingName("UTF-8");
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        mMyWebView.setVisibility(View.VISIBLE);
        mMyWebView.setWebChromeClient(new WebChromeClient());

        if (!TextUtils.isEmpty(model.webUrl) && !hasLoad) {
            mMyWebView.setVisibility(View.VISIBLE);
            mMyWebView.loadUrl(H5Address.FORWARD_APP + model.webUrl);
//            mMyWebView.loadUrl("http://player.youku.com/embed/XNTM5MTUwNDA0");
            hasLoad = true;
        } else {
            mMyWebView.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onResume() {
        try {
            mMyWebView.getClass().getMethod("onResume").invoke(mMyWebView, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onResume();
    }

    /**
     * 解决退出仍有声音的bug
     */
    @Override
    protected void onPause() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//            mMyWebView.onPause(); // 暂停网页中正在播放的视频
//        }
        try {
            mMyWebView.getClass().getMethod("onPause").invoke(mMyWebView, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onPause();
    }

    /**
     * 处理标签
     */
    public void handTag() {
        final List<TagModel> tags = model.tagList;
        //标签
        if (null != tags && !tags.isEmpty()) {
            mTxtTag.setVisibility(View.VISIBLE);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < tags.size(); i++) {
                TagModel model = tags.get(i);
                String str = "<table width = '300' height = '400' border = '10' bordercolor='#333333'><font color='#E69215'><tag>" + " #" + model.tagName + "# " + "</tag></font></table>" + "、";
                sb.append(str);
            }
            sb.deleteCharAt(sb.length() - 1);
            mTxtTag.setText(Html.fromHtml(sb.toString(), null, new Html.TagHandler() {
                int sIndex = 0;
                int eIndex = 0;

                @Override
                public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
                    if (opening) {
                        if (tag.toLowerCase().equals("tag")) {
                            sIndex = output.length();
                        }
                    } else {
                        if (tag.toLowerCase().equals("tag")) {
                            eIndex = output.length();
                            output.setSpan(new MxgsaSpan(tags, output.toString()), sIndex, eIndex, Spanned.SPAN_MARK_MARK);
                        }
                    }
                }
            }));
            mTxtTag.setClickable(true);
            mTxtTag.setMovementMethod(LinkMovementMethod.getInstance());
            mTxtTag.setOnTouchListener(new LinkMovementMethodOverride());
        } else {
            mTxtTag.setVisibility(View.GONE);
        }
    }

    /**
     * 标签的点击事件
     */
    private class MxgsaSpan extends ClickableSpan implements View.OnClickListener {
        private String mstr;
        private List<TagModel> tags;

        public MxgsaSpan(List<TagModel> tags, String mstr) {
            this.mstr = mstr;
            this.tags = tags;
        }

        @Override
        public void onClick(View widget) {
            String msg = mstr.replaceAll("#", "").replaceAll(" ", "").trim();
            TagModel tagModel = null;
            String mSave = "";
            if (msg.contains("、")) {
                String[] split = msg.split("、");
                for (TagModel model : tags) {
                    if (TextUtils.equals(model.tagName, split[split.length - 1])) {
                        tagModel = model;
                    } else {
                        mSave = split[split.length - 1];
                    }
                }
            } else {
                TagModel model = tags.get(0);
                tagModel = model;
            }
            if (null != tagModel) {
                Intent intent = new Intent(aty, CheerCircleAty.class);
                intent.putExtra(IntentKey.General.KEY_ID, tagModel.getId());
                intent.putExtra(IntentKey.General.KEY_DES, tagModel.getTitle());
                startActivity(intent);
            } else {
                ToastUtil.showToast(mSave);
            }
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setColor(App.getContext().getResources().getColor(R.color.color_main));
            ds.setUnderlineText(false);
        }
    }

    /**
     * 禁止标签上下滑动
     */
    public class LinkMovementMethodOverride implements View.OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            TextView widget = (TextView) v;
            Object text = widget.getText();
            if (text instanceof Spanned) {
                Spanned buffer = (Spanned) text;

                int action = event.getAction();

                if (action == MotionEvent.ACTION_UP
                        || action == MotionEvent.ACTION_DOWN) {
                    int x = (int) event.getX();
                    int y = (int) event.getY();

                    x -= widget.getTotalPaddingLeft();
                    y -= widget.getTotalPaddingTop();

                    x += widget.getScrollX();
                    y += widget.getScrollY();

                    Layout layout = widget.getLayout();
                    int line = layout.getLineForVertical(y);
                    int off = layout.getOffsetForHorizontal(line, x);

                    ClickableSpan[] link = buffer.getSpans(off, off,
                            ClickableSpan.class);

                    if (link.length != 0) {
                        if (action == MotionEvent.ACTION_UP) {
                            link[0].onClick(widget);
                        } else if (action == MotionEvent.ACTION_DOWN) {
                            // Selection only works on Spannable text. In our case setSelection doesn't work on spanned text
                            //Selection.setSelection(buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0]));
                        }
                        return true;
                    }
                }
            }
            return false;
        }
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.GET_LIKES_SUCCESS)) {
                mXRefreshView.stopRefresh();
                //获得点赞列表成功
                List<CommentModel> mZanList = (List<CommentModel>) t;
                if (null != mZanList && !mZanList.isEmpty()) {
                    mSaveZanList.clear();
                    mSaveZanList.addAll(mZanList);
                    handZan();
                }
            } else if (TextUtils.equals(tag, ConstantTag.LIKE_SUCCESS)) {
                //点赞成功
                model.goodStatus = 1;
                model.goodCount += 1;
                mSaveZanList.add(mSaveUserZan);

                handZan();
                BaseEvent event = new BaseEvent();
                event.type = ConstantTag.LIKE_SUCCESS;
                EventBus.getDefault().post(event);

                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA;
                EventBus.getDefault().post(del);
            } else if (TextUtils.equals(tag, ConstantTag.DEL_LIKE_SUCCESS)) {
                //取消点赞成功
                model.goodStatus = 0;
                model.goodCount -= 1;
                mSaveZanList.remove(mSaveUserZan);
                handZan();
                BaseEvent event = new BaseEvent();
                event.type = ConstantTag.DEL_LIKE_SUCCESS;
                EventBus.getDefault().post(event);

                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA;
                EventBus.getDefault().post(del);
            } else if (TextUtils.equals(tag, "1")) {
                //评论
                String context = (String) t;
                ((CommentPresenter) presenter).userComment(false, context, model.sourceType, model.sourceId, "");
            } else if (TextUtils.equals(tag, ConstantTag.COMMENT_SUCCESS)) {
                //评论成功
                ToastUtil.showToast("评论成功");
                CommentModel commentModel = (CommentModel) t;
                if (null == commentModel) {
                    commentModel = new CommentModel();
                }
                commentModel.custNname = Session.getUserName();
                commentModel.custImg = Session.getUserPicUrl().replace(OssManager.OSS_HOST, "");
                commentModel.custId = Session.getUserId();
                mTotalModel.add(0, commentModel);
                model.commentCount += 1;
                handComment();

                BaseEvent event = new BaseEvent();
                event.type = ConstantTag.COMMENT_SUCCESS;
                event.model = commentModel;
                EventBus.getDefault().post(event);

                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA;
                EventBus.getDefault().post(del);
            } else if (TextUtils.equals(tag, "2")) {
                //回复
                String context = (String) t;
                ((CommentPresenter) presenter).userReply(false, context, model.sourceType, model.sourceId, mRecordCommentItem.custId, mRecordCommentItem.uid);
            } else if (TextUtils.equals(tag, ConstantTag.REPLY_SUCCESS)) {
                //回复成功
                ToastUtil.showToast("回复成功");
                CommentModel replyModel = (CommentModel) t;
                if (null == replyModel) {
                    replyModel = new CommentModel();
                }
                replyModel.custNname = Session.getUserName();
                replyModel.custImg = Session.getUserPicUrl().replace(OssManager.OSS_HOST, "");
                replyModel.custId = Session.getUserId();
                replyModel.replyCustNname = mRecordCommentItem.custNname;
                replyModel.replyCustImg = mRecordCommentItem.custImg;
                replyModel.replyCustId = mRecordCommentItem.custId;
                mTotalModel.add(0, replyModel);
                model.commentCount += 1;
                handComment();

                BaseEvent event = new BaseEvent();
                event.type = ConstantTag.REPLY_SUCCESS;
                event.model = replyModel;
                EventBus.getDefault().post(event);

                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA;
                EventBus.getDefault().post(del);
            } else if (TextUtils.equals(tag, ConstantTag.DEL_COMMENT_SUCCESS)) {
                ToastUtil.showToast("评论删除成功");
                //删除评论或者回复
                for (CommentModel model : mTotalModel) {
                    if (TextUtils.equals(model.uid, mRecordCommentItem.uid)) {
                        model.delFlag = 1;
                        mCommentAdp.notifyDataSetChanged();
                        break;
                    }
                }
                BaseEvent event = new BaseEvent();
                event.type = ConstantTag.DEL_COMMENT_SUCCESS;
                event.model = mRecordCommentItem;
                EventBus.getDefault().post(event);

                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA;
                EventBus.getDefault().post(del);
            } else if (TextUtils.equals(ConstantTag.DEL_DYNAMIC, tag)) {
                //动态删除
                SVProgressHUD.showInfoWithStatus(aty, "删除成功");
                BaseEvent event = new BaseEvent();
                event.type = ConstantTag.DEL_DYNAMIC;
                EventBus.getDefault().post(event);

                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA;
                EventBus.getDefault().post(del);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 2000);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(aty).onActivityResult(requestCode, resultCode, data);
    }
}
